const { Sequelize } = require('sequelize');
const mysql = require('mysql2/promise');
const dotenv = require('dotenv');

// 确保环境变量已加载
dotenv.config();

const DB_NAME = process.env.DB_NAME || 'mars_intelligence';
const DB_USER = process.env.DB_USER || 'root';
const DB_PASSWORD = process.env.DB_PASSWORD || '123456';
const DB_HOST = process.env.DB_HOST || 'localhost';
const DB_PORT = process.env.DB_PORT || 3306;

const sequelize = new Sequelize(
  DB_NAME,
  DB_USER,
  DB_PASSWORD,
  {
    host: DB_HOST,
    port: DB_PORT,
    dialect: 'mysql',
    logging: false,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  }
);

// 创建数据库（如果不存在）
const createDatabaseIfNotExists = async () => {
  try {
    // 创建没有指定数据库的连接
    const connection = await mysql.createConnection({
      host: DB_HOST,
      port: DB_PORT,
      user: DB_USER,
      password: DB_PASSWORD
    });
    
    // 创建数据库
    await connection.query(`CREATE DATABASE IF NOT EXISTS ${DB_NAME}`);
    console.log(`数据库 ${DB_NAME} 已创建或已存在`);
    
    // 关闭连接
    await connection.end();
  } catch (error) {
    console.error('创建数据库失败:', error);
    process.exit(1);
  }
};

const connectDB = async () => {
  try {
    // 先创建数据库
    await createDatabaseIfNotExists();
    
    // 然后连接到数据库
    await sequelize.authenticate();
    console.log('MySQL数据库连接成功');
  } catch (error) {
    console.error('MySQL数据库连接失败:', error);
    process.exit(1);
  }
};

module.exports = { sequelize, connectDB };  